package com.fading.mall.product.app;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fading.mall.product.entity.CategoryBrandRelationEntity;
import com.fading.mall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import com.fading.mall.product.entity.BrandEntity;
import com.fading.mall.product.service.BrandService;
import com.fading.common.utils.PageUtils;
import com.fading.common.utils.R;

import javax.validation.Valid;


/**
 * 品牌
 *
 * @author fadingYY
 * @email 2714592747@qq.com
 * @date 2021-08-11 16:21:42
 */
@RestController
@RequestMapping("product/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = brandService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{brandId}")
    public R info(@PathVariable("brandId") Long brandId){
		BrandEntity brand = brandService.getById(brandId);

        return R.ok().put("brand", brand);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@Valid @RequestBody BrandEntity brand, BindingResult result){
        if(result.hasErrors()){
            Map<String,String> map = new HashMap<>();
            result.getFieldErrors().forEach((error)->
                    map.put(error.getField(), error.getDefaultMessage()));
            return R.error(400,"校验失败").put("error", map);
        }else {
            brandService.save(brand);
            return R.ok();
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody BrandEntity brand){
		brandService.updateById(brand);
        CategoryBrandRelationEntity relationEntity = new CategoryBrandRelationEntity();
        String brandName = brand.getName();
        Long brandId = brand.getBrandId();
        relationEntity.setBrandName(brandName);
        categoryBrandRelationService.update(relationEntity,new UpdateWrapper<CategoryBrandRelationEntity>().eq("brand_id", brandId));
        return R.ok();
    }

    @RequestMapping("/update/status")
    public R updateStatus(@RequestBody BrandEntity brand){
        brandService.updateById(brand);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@Valid @RequestBody Long[] brandIds){
		brandService.removeByIds(Arrays.asList(brandIds));

        return R.ok();
    }

}
